﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;

namespace TamilManam
{
    public partial class Page1 : PhoneApplicationPage
    {
        private String pageTitle = "";
        private String feedUrl = "";
        public Page1()
        {
            InitializeComponent();
        }

        private String printerFriendlyUrl = "";
        private String actualPageUrl = "";

        private void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e)
        {
            NavigationContext.QueryString.TryGetValue("pageHeading", out pageTitle);
            NavigationContext.QueryString.TryGetValue("selectedUri", out feedUrl);
            textBlock.Text = pageTitle;
            getHtmlText(feedUrl, pageTitle);
        }
		
        public void RequestComplete(object sender, OpenReadCompletedEventArgs e)
        {
            string response = "";

            using (var reader = new StreamReader(e.Result))
            {
                response = reader.ReadToEnd();
                Console.Write("read details = " + response);
                parseHtmlText(response, pageTitle);
            }
        }

        private void parseBlogText(string text){
	    var idx = text.LastIndexOf("print this page");
	    if(idx < 0){
//	        errorCallback("Parse Error")
	        return;
	    }
	
	    // size of (print this page"></a>) = 21
        var neededTxt = text.Substring(idx + 21, text.Length - (idx + 21));
	    Console.Write("the text to be printed is " + neededTxt);
        wb.Source = new Uri(printerFriendlyUrl);
            
        //contextTextBlock.Text = neededTxt;
	}


        public void PrinterPageRequestComplete(object sender, OpenReadCompletedEventArgs e)
        {
            string response = "";

            using (var reader = new StreamReader(e.Result))
            {
                response = reader.ReadToEnd();
                Console.Write("read printer details = " + response);
                parseBlogText(response);
            }
        }


        private void getHtmlText(string url, string title){
            Console.Write("getHtmlText IN");

            WebClient web = new WebClient();
            web.OpenReadCompleted += new OpenReadCompletedEventHandler(RequestComplete);
            web.OpenReadAsync(new Uri(url));
        }

        private void getBlogText(string printerUrl)
        {
            WebClient web = new WebClient();
            web.OpenReadCompleted += new OpenReadCompletedEventHandler(PrinterPageRequestComplete);
            web.OpenReadAsync(new Uri(printerUrl));
        }
        

    private void parseHtmlText(string text, string title){
        var doc = new Object();
        var result = new Object();
        //console.debug("html text to be parsed " + text)
        var textLen = text.Length;
        Console.Write("title to be found " + title);

        var lastIdx = text.LastIndexOf(title);
        Console.Write("last index of title found at " + lastIdx);

        var neededTxt = text.Substring(0, lastIdx);
        var lastHrefIdx = neededTxt.LastIndexOf("<a href=");
        var preFinalTxt = neededTxt.Substring(lastHrefIdx, lastIdx - lastHrefIdx);

        Console.Write("last few text which has link is " + preFinalTxt);

        var urlIdx = preFinalTxt.IndexOf("url=");
        var idIdx = preFinalTxt.IndexOf("&id=");

        var url = preFinalTxt.Substring(urlIdx + 4, idIdx - urlIdx + 4);
        Console.Write("final url is " + url);

        actualPageUrl = url;

        var idx = text.IndexOf("/printer_friendly.php");
        var pFriendlyTxt = text.Substring(idx, text.Length - idx);
        idx = pFriendlyTxt.IndexOf("'");
        pFriendlyTxt = pFriendlyTxt.Substring(0, idx);
        Console.Write("text with printer friendly text " + pFriendlyTxt);
        printerFriendlyUrl = "http://www.tamilmanam.net/" + pFriendlyTxt;

        getBlogText(printerFriendlyUrl);
        //dataCallback(result)

        //var res = htmlToXML(text.substring(0,10));
        //console.debug("html parsing result is " + res)
    }

    private void onTapped(object sender, System.Windows.Input.GestureEventArgs e)
    {
        NavigationService.Navigate(new Uri("/WebPage.xaml?selectedUri=" + actualPageUrl, UriKind.Relative));
    }

    }
}